<template>
	<div
		v-if="workflowStore.state.nodePortMenu.visible 
		&& workflowStore.state.nodePortMenu.port.type=='exec'"
		class="context-menu"
		:style="{
			position: 'fixed',
			top: `${workflowStore.state.nodePortMenu.position.y}px`,
			left: `${workflowStore.state.nodePortMenu.position.x}px`,
			zIndex: 99999,
		}"
	>
	  <div 
	    v-for="(item, index) in items" 
	    :key="index"
	    class="menu-item"
	    :class="{ 'disabled': item.disabled }"
	    @click="!item.disabled && item.handler()"
	    @mousedown.stop
	  >
	    {{ item.label }}
	  </div>
	</div>
</template>

<script setup lang="ts">
	
	import { ref } from 'vue';
	import type { WorkflowNode as FlowNode } from '@/stores/workflow';
	import { useWorkflowStore } from '@/stores/workflow';
	import { v4 as uuidv4 } from 'uuid';
	import { ElMessage } from 'element-plus';
	import { onMounted } from 'vue';
	import { watch } from 'vue';
	
	const workflowStore = useWorkflowStore();
	const visible = ref<boolean>(false);
	const targetNode = ref<FlowNode | undefined>();
	let svgContainer = ref<SVGSVGElement | null>(null);
	const items = ref<any[]>([]);
	const postion = ref<any>({
		top:0,
		left:0
	});
	
	const props = defineProps<{
	  svgContainer: SVGSVGElement;
	}>();

	defineEmits<{
	  (e: 'close'): void;
	}>();
	
	// 修改菜单项配置为函数
	const getMenuItems = (output: any) => {
	  if (!targetNode.value || !output) return [];
	  
	  const portId = `output-${targetNode.value.id}-${output.id}-port`;
	  const isExecType = output.type === 'exec';
	  
	  if (!isExecType) return [];
	  
	  return [
	    {
	      label: '在前方加入执行引脚',
	      handler: () => handleCommand('addBefore', portId)
	    },
	    {
	      label: '在后方加入执行引脚',
	      handler: () => handleCommand('addAfter', portId)
	    },
	    {
	      label: '断开此连接',
	      handler: () => handleCommand('disconnect', portId),
	      show: isPortConnected(portId)
	    },
	    {
	      label: '移除执行引脚',
	      handler: () => handleCommand('delete', portId),
	      disabled: targetNode.value?.data.outputs.length <= 3
	    }
	  ].filter(item => item.show !== false);
	};
	
	// 检查端口是否已连接
	const isPortConnected = (portId: string): boolean => {
	  return workflowStore.state.connections.some((conn: { sourcePortId: string; targetPortId: string; }) => 
	    conn.sourcePortId === portId || conn.targetPortId === portId
	  );
	};
	
	// 处理命令
	const handleCommand = (command: string, portId: string) => {
	  if (!targetNode.value) return;
	  
	  const currentIndex = targetNode.value.data.outputs.findIndex((out: { id: any; }) => 
	    `output-${targetNode.value?.id}-${out.id}-port` === portId
	  );
	  
	  if (currentIndex === -1) return;
	  
	  // 获取节点所有输出端口的连接
	  const nodeConnections = workflowStore.state.connections.filter((conn: { sourcePortId: string; }) => {
	    // 检查连接的源端口是否属于当前节点的任何输出端口
	    return targetNode.value?.data.outputs.some((output: { id: any; }) => 
	      `output-${targetNode.value?.id}-${output.id}-port` === conn.sourcePortId
	    );
	  });
	  
	  switch (command) {
	    case 'addBefore':{
	      // 在当前端口前添加新的执行端口
	      const newOutputBefore = {
			code: "exec",
			id: uuidv4(),
			name: "Then",
			type: "exec",
			value: "",
			click:"1",
			fieldType:'any'
	      };
	      targetNode.value.data.outputs.splice(currentIndex, 0, newOutputBefore);
	      // 更新所有受影响的连接
	      if (nodeConnections.length > 0) {
			  if(svgContainer.value) workflowStore.updatedNodeConnections(nodeConnections,svgContainer.value);
	      }
		  close();
	      break;
	    }
	    case 'addAfter': {
	      const newOutputAfter = {
	        code: "exec",
	        id: uuidv4(),
	        name: "Then",
	        type: "exec",
	        value: "",
			click:"1",
			fieldType:'any'
	      };
	      targetNode.value.data.outputs.splice(currentIndex + 1, 0, newOutputAfter);
	      
	      if (nodeConnections.length > 0) {
				 if(svgContainer.value)  workflowStore.updatedNodeConnections(nodeConnections,svgContainer.value);
	      }
		  close();
	      break;
	    }
	    case 'disconnect':
	      workflowStore.removeConnectionsByPortId(portId);
		  close();
	      break;
	    case 'delete':
	      if (targetNode.value.data.outputs.filter((out: { type: string; }) => out.type === 'exec').length <= 2) {
	        ElMessage.warning('必须保留至少两个执行端口');
			close();
	        return;
	      }
	      workflowStore.removeConnectionsByPortId(portId);
	      targetNode.value.data.outputs.splice(currentIndex, 1);
		  close();
	      break;
	  }
	  workflowStore.incrementVersion();
	  close();
	};
	
	const open=(portId: string, node: FlowNode, event: MouseEvent,container:SVGSVGElement)=>{
		svgContainer.value=container;
		targetNode.value = node;
		// 找到当前点击的输出端口
		const currentOutput = node.data.outputs.find((out: { id: any; }) => 
			`output-${node.id}-${out.id}-port` === portId
		);
		
		if (currentOutput) {
			items.value = getMenuItems(currentOutput);
		}
		
		postion.value.top = event.clientY + 'px';
		postion.value.left = event.clientX + 'px';
		visible.value = true;
	}
	
	const close=()=>{
		workflowStore.hideNodePortMenu();
	}
	
	defineExpose({
	  open,close
	});
	
	// 监听整个 nodePortMenu 对象
	watch(() => workflowStore.state.nodePortMenu, (newValue) => {
	  if (newValue.visible && newValue.port) {
	    targetNode.value = newValue.node || undefined;
	    svgContainer.value = props.svgContainer;
	    items.value = getMenuItems(newValue.port);
	  }
	}, { deep: true });
	
	onMounted(() => {

	});
	
</script>

<style lang="scss" scoped>
.menu-container {
  pointer-events: all;
}

.context-menu {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);
  background-color: #252526;
  .menu-item {
    padding: 8px 16px;
    color: #fff;
    cursor: pointer;
    transition: all 0.2s;
    white-space: nowrap;
    font-size: 12px;
    line-height: 1.5;
    
    &:hover {
      background: rgba(64, 158, 255, 0.1);
      color: #409EFF;
    }
    
    &.disabled {
      color: #666;
      cursor: not-allowed;
      
      &:hover {
        background: none;
        color: #666;
      }
    }
  }
}
</style> 